<template>
  <view class="appointment-detail-page">
    <view class="page-header">
      <text class="page-title">预约详情</text>
      <view class="header-actions">
        <button class="btn-action btn-back" @click="handleBack">返回</button>
        <button class="btn-action btn-edit" @click="handleEdit">编辑</button>
        <button class="btn-action btn-delete" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <!-- 预约信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">预约信息</text>
          <view :class="['status-badge', getStatusClass(appointment.status)]">
            {{ getStatusText(appointment.status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">预约号</text>
            <text class="value">{{ formatAppointmentNo(appointment.appointment_no) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">患者姓名</text>
            <text class="value">{{ patientName || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">医生姓名</text>
            <text class="value">{{ doctorName || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">预约时间</text>
            <text class="value">{{ appointment.appointment_date }} {{ appointment.appointment_time }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">预计时长</text>
            <text class="value">{{ formatDuration(appointment.duration_minutes) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">首复诊</text>
            <text class="value">{{ getVisitTypeText(appointment.visit_type) }}</text>
          </view>
          
          <view v-if="appointment.chief_complaint" class="detail-row vertical">
            <text class="label">主诉</text>
            <text class="value">{{ appointment.chief_complaint }}</text>
          </view>
        </view>
      </view>

      <!-- 诊断处方 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">诊断与处方</text>
        </view>
        <view class="card-body">
          <view class="detail-row vertical">
            <text class="label">诊断结果</text>
            <text class="value">{{ appointment.diagnosis || '暂无' }}</text>
          </view>
          
          <view class="detail-row vertical">
            <text class="label">处方内容</text>
            <text class="value">{{ appointment.prescription || '暂无' }}</text>
          </view>
          
          <view class="detail-row vertical">
            <text class="label">治疗计划</text>
            <text class="value">{{ appointment.treatment_plan || '暂无' }}</text>
          </view>
        </view>
      </view>

      <!-- 支付信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">支付信息</text>
          <view :class="['payment-badge', getPaymentStatusClass(appointment.payment_status)]">
            {{ getPaymentStatusText(appointment.payment_status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">支付方式</text>
            <text class="value">{{ getPaymentMethodText(appointment.payment_method, appointment.payment_status) }}</text>
          </view>
          
          <view v-if="appointment.payment_amount" class="detail-row">
            <text class="label">支付金额</text>
            <text class="value">¥{{ appointment.payment_amount }}</text>
          </view>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(appointment.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(appointment.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const loading = ref(true)
const appointmentId = ref('')
const patientName = ref('')
const doctorName = ref('')
const isFirstLoad = ref(true)

const appointment = reactive({
  appointment_no: '',
  patient_id: '',
  doctor_id: '',
  appointment_date: '',
  appointment_time: '',
  duration_minutes: 0,
  visit_type: 1,
  chief_complaint: '',
  diagnosis: '',
  prescription: '',
  treatment_plan: '',
  payment_status: 0,
  payment_method: 0,
  payment_amount: 0,
  status: 1,
  create_time: null,
  update_time: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  appointmentId.value = currentPage.options.id || ''
  
  if (!appointmentId.value) {
    uni.showToast({ title: '缺少预约ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/appointments/list' })
    }, 1500)
    return
  }
  
  await loadAppointmentData()
  loading.value = false
})

// 页面显示时刷新数据
onShow(async () => {
  // 跳过首次加载，因为 onMounted 已经加载过了
  if (isFirstLoad.value) {
    isFirstLoad.value = false
    return
  }
  
  if (appointmentId.value) {
    loading.value = true
    await loadAppointmentData()
    loading.value = false
  }
})

async function loadAppointmentData() {
  try {
    const appointmentsObj = uniCloud.importObject('dh-appointments')
    const res = await appointmentsObj.getAppointmentById(appointmentId.value)
    
    if (res.code === 200 && res.data) {
      Object.assign(appointment, res.data)
      // 云函数已经返回了 patient_name 和 doctor_name
      patientName.value = res.data.patient_name || '未知用户'
      doctorName.value = res.data.doctor_name || '未知医生'
    } else {
      throw new Error(res.message || '预约不存在')
    }
  } catch (err) {
    console.error('加载预约数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/appointments/list' })
    }, 1500)
  }
}

// 格式化预约号
function formatAppointmentNo(appointmentNo) {
  if (!appointmentNo) return '暂无'
  if (appointmentNo.startsWith('APT') && appointmentNo.length >= 14) {
    const year = appointmentNo.substring(5, 7)
    const month = parseInt(appointmentNo.substring(7, 9))
    const day = parseInt(appointmentNo.substring(9, 11))
    const number = appointmentNo.substring(11)
    return `${year}年${month}月${day}日${number}号`
  }
  return appointmentNo
}

// 格式化时长
function formatDuration(minutes) {
  if (!minutes) return '暂无'
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  if (remainingMinutes === 0) {
    return `${hours}小时`
  }
  return `${hours}小时${remainingMinutes}分钟`
}

// 获取就诊类型文本
function getVisitTypeText(visitType) {
  const typeMap = {
    1: '初诊',
    2: '复诊'
  }
  return typeMap[visitType] || '未知'
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: '已预约',
    2: '已就诊',
    3: '未到诊',
    4: '已取消',
    5: '医生拒诊'
  }
  return statusMap[status] || '未知'
}

// 获取状态样式类
function getStatusClass(status) {
  const classMap = {
    1: 'status-pending',
    2: 'status-completed',
    3: 'status-no-show',
    4: 'status-cancelled',
    5: 'status-cancelled'
  }
  return classMap[status] || 'status-pending'
}

// 获取支付状态文本
function getPaymentStatusText(status) {
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '已退款'
  }
  return statusMap[status] || '未知'
}

// 获取支付状态样式类
function getPaymentStatusClass(status) {
  const classMap = {
    0: 'payment-unpaid',
    1: 'payment-paid',
    2: 'payment-refunded'
  }
  return classMap[status] || 'payment-unpaid'
}

// 获取支付方式文本
function getPaymentMethodText(method, paymentStatus) {
  if (paymentStatus !== 1) {
    return '-'
  }
  const methodMap = {
    1: '微信支付',
    2: '支付宝',
    3: '现金'
  }
  return methodMap[method] || '未知'
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 返回
function handleBack() {
  uni.navigateBack()
}

// 编辑
function handleEdit() {
  uni.navigateTo({
    url: `/pages/business/appointments/edit?id=${appointmentId.value}`
  })
}

// 删除
async function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条预约记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const appointmentsObj = uniCloud.importObject('dh-appointments')
          const result = await appointmentsObj.deleteAppointment(appointmentId.value)
          
          if (result.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/appointments/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'error' })
          }
        } catch (error) {
          console.error('删除失败:', error)
          uni.showToast({ title: '删除失败', icon: 'error' })
        }
      }
    }
  })
}
</script>

<style scoped>
.appointment-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
}

.page-header {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
}

.btn-action {
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  font-weight: 500;
}

.btn-back {
  background: #e8e8e8;
  color: #333;
}

.btn-edit {
  background: #007aff;
  color: white;
}

.btn-delete {
  background: #ff3b30;
  color: white;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f0f0f0;
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.detail-card {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge, .payment-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background: #fff3e0;
  color: #ff9800;
}

.status-completed {
  background: #e8f5e9;
  color: #4caf50;
}

.status-no-show {
  background: #ffebee;
  color: #f44336;
}

.status-cancelled {
  background: #f5f5f5;
  color: #9e9e9e;
}

.payment-unpaid {
  background: #ffebee;
  color: #f44336;
}

.payment-paid {
  background: #e8f5e9;
  color: #4caf50;
}

.payment-refunded {
  background: #fff3e0;
  color: #ff9800;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16rpx 0;
}

.detail-row.vertical {
  flex-direction: column;
  gap: 12rpx;
}

.label {
  color: #666;
  font-size: 28rpx;
  min-width: 160rpx;
}

.value {
  color: #333;
  font-size: 28rpx;
  flex: 1;
  text-align: right;
  word-break: break-all;
}

.detail-row.vertical .value {
  text-align: left;
}
</style>
